/**
 * This class is an extension to Openswing's
 */
package slhs.tempo.pivotTableUtilities;

import java.io.Serializable;
import java.util.ArrayList;

import org.openswing.swing.pivottable.functions.java.AverageFunction;

/**
 * StandardDeviationFunction.java
 * 
 * @author Swapnil Devikar
 * 
 */
public class StandardDeviationFunction extends AverageFunction implements Serializable {

    private ArrayList<Double> dataPoints;

    public StandardDeviationFunction() {
	dataPoints = new ArrayList<Double>();
    }

    @Override
    public void processValue(Object value) {
	if (value != null && value instanceof Number) {
	    super.processValue(value);
	    dataPoints.add(new Double(((Number) value).doubleValue()));
	}
    }

    @Override
    public Double getValue() {
	if ((dataPoints.size() != 0) && super.getValue() != null) {
	    double differenceSquaredSum = 0;
	    double mean = super.getValue().doubleValue();
	    for (Double value : dataPoints) {
		Double difference = value - mean;
		Double differenceSquared = difference * difference;
		differenceSquaredSum += differenceSquared;
	    }
	    return Math.sqrt(differenceSquaredSum / dataPoints.size());
	}

	return null;
    }
}
